package cn.yq.aio.ui.main.shengao;

import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.util.List;

import cn.yq.aio.base.MyApp;
import cn.yq.aio.databinding.FragmentShenGaoBinding;
import cn.yq.aio.utils.BleUtils;
import cn.yq.aio.utils.SystemUtils;
import cn.yq.aio.utils.recycler.TShow;

/**
 * @AUTHOR YangLu
 * @Time 2021-03-25
 * @todo 身高体重
 */
public class ShenGaoFragment extends Fragment {

    public ShenGaoFragment() {
        // Required empty public constructor
    }

    public static ShenGaoFragment newInstance() {
        ShenGaoFragment shenGaoFragment = new ShenGaoFragment();
        return shenGaoFragment;
    }

    FragmentShenGaoBinding binding;
    BleUtils bleUtils;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentShenGaoBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.getRoot().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (binding.tipsShenGaoFrg.getVisibility() == View.VISIBLE) {
                    binding.tipsShenGaoFrg.setVisibility(View.GONE);
                }
                return false;
            }
        });
        binding.rightMain.titleRightMainFrg.setText("身高测量");
        binding.rightMain.measureRightMainFrg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkStart();
            }
        });
        binding.tipsShenGaoFrg.setText("--");
    }

    private void checkStart() {
        if (!getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            TShow.show("该设备不支持蓝牙");
            return;
        }
        if (bleUtils != null) {
            TShow.show("等待本次测量完成再开始监测");
            return;
        }
        XXPermissions.with(this).permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (!SystemUtils.isGpsEnable()) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                            builder.setCancelable(false);
                            builder.setTitle("提示")
                                    .setIcon(android.R.drawable.ic_menu_info_details)
                                    .setMessage("蓝牙链接需要开启GPS定位")
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    }).setPositiveButton("开启",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent =
                                                    new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivity(intent);
                                        }
                                    });
                            builder.show();
                            return;
                        }
                        readyStart();
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        TShow.show("蓝牙链接需要开启定位权限");
                    }
                });
    }

    private void readyStart() {
        showTips("开始扫描设备...");//mGattUpdateReceiver 回调

        bleUtils = new BleUtils(getActivity(), new BleUtils.CallBack() {
            @Override
            public boolean isNeedDevice(String bleDeviceName) {
                return !TextUtils.isEmpty(bleDeviceName) &&
                        (bleDeviceName.contains("irxon"));
            }

            @Override
            public boolean needConnect(BluetoothDevice td) {
                showTips("已找到设备，准备连接...");
                return true;
            }

            @Override
            public boolean isNeedService(String uuid) {
                return true;
            }

            @Override
            public boolean isNeedCharacteristic(String uuid) {
                return true;
            }

            @Override
            public void findCharacteristic(BluetoothGattCharacteristic characteristic) {
                bleUtils.notify(characteristic);
            }

            @Override
            public void breakConnect() {
                MyApp.getInstance().handler.post(new Runnable() {
                    @Override
                    public void run() {
                        showTips("蓝牙连接已断开");
                        end();
                    }
                });
            }

            @Override
            public void onReceiveValue(byte[] data) {

            }
        });
        bleUtils.open(false);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
        end();
    }

    private void end() {
        if (bleUtils != null)
            bleUtils.close();
        bleUtils = null;
    }

    private void showTips(String msg) {
        binding.tipsShenGaoFrg.setVisibility(View.VISIBLE);
        binding.tipsShenGaoFrg.setText(msg);
    }

    private void hideTips() {
        binding.tipsShenGaoFrg.setVisibility(View.GONE);
    }
}
